<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Article;
use App\Constants\MiniProgramConstant;
use App\Constants\TagConstant;
use App\Models\ArticleComment;
use App\Models\Publisher;
use App\Models\Tag;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Tab;

class NewsArticleController extends AdminController
{
    public function index(Content $content)
    {
        $tab = Tab::make();
//        $tab->addLink('热点快讯', admin_route('hot_articles.index'));
        $tab->add('新闻资讯', $this->grid(), true);
        $tab->addLink('标签', admin_route('article_tags.index'));
        $tab->addLink('草稿箱', admin_route('news_articles_draft.index'));
        return $content->body($tab->withCard());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Article(['tag']), function (Grid $grid) {
            $map = getAuthMiniProgramMap(Admin::user()->id);
            $grid->model()->whereIn('mini_type', array_keys($map));

            $grid->model()->where('type', '=', 2);
            $grid->model()->orderByDesc('created_at');
            $grid->column('created_at');
            $grid->column('mini_type')->display(function ($miniType) use($map) {
                return $miniType ? $map[$miniType] : '';
            });
            $grid->column('id');
            $grid->column('mini_app_short_link', '小程序短链')->display('查看')->modal(function ($modal) {
                $modal->title('小程序短链');
                $modal->icon('');

                $id = $this->id;
                $link = $this->mini_app_short_link;

                return admin_view('admin.article.short_link', compact('id', 'link'));
            });
            $grid->column('title');
            $grid->column('tag.name', '标签');
            $grid->column('thum_img')->image('/uploads', 50, 50);
            $grid->column('is_hot')->using(['否', '是'])->label([
                'danger', 'primary'
            ]);
            $grid->column('is_top')->using(['否', '是'])->label([
                'danger', 'primary'
            ]);

            $grid->disableFilterButton();
            $grid->disableRefreshButton();
            $grid->disableBatchDelete();
            $grid->disableViewButton();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append('<a style="margin-right:5px" href="'.admin_route('article_comments.index', ['article_id' => $actions->row->id]).'">查看评论</a>');
                $actions->append('<a style="margin-right:5px" href="'.admin_route('article_comments.create', ['article_id' => $actions->row->id]).'">添加评论</a>');
            });

            $grid->filter(function (Grid\Filter $filter) use($map) {
                $filter->panel();
                $filter->expand();
                $filter->equal('mini_type')->select($map)->width(2);
                $filter->equal('id')->width(2);
                $filter->like('title')->width(2);
                $filter->between('created_at')->datetime()->width(4);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Article(), function (Show $show) {
            $show->field('id');
            $show->field('publish_id');
            $show->field('type');
            $show->field('title');
            $show->field('desc');
            $show->field('file_type');
            $show->field('file_ids');
            $show->field('thum_img');
            $show->field('content');
            $show->field('is_hot');
            $show->field('is_top');
            $show->field('first_relay_count');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Article(), function (Form $form) {
            $form->display('id');
            $form->select('mini_type')->options(function (){
                return getAuthMiniProgramMap(Admin::user()->id);
            })->required();
            $form->hidden('type')->value('2');
            $publishers = Publisher::all()->pluck('name', 'id');
            $form->select('publish_id')->required()->options($publishers);
            $form->text('title')->required();
            $form->text('desc')->rules('required|string|max:255', [
                'required' => '描述必填',
                'max' => '描述字数不能大于255个',
            ]);;
            $form->image('thum_img', '缩略图')->required()->saveFullUrl()->uniqueName()->autoUpload()->help('建议尺寸: 750X560PX');
            $form->select('tag_id', '标签')->required()->options(Tag::where('type', '=', TagConstant::TAG_BY_ARTICLE)->pluck('name', 'id')->all());
            $form->ueditor('content')->required();
            $form->radio('is_hot')->options(['否', '是'])->default('0');
            $form->radio('is_top')->options(['否', '是'])->default('0');
            $form->text('first_relay_count')->default(0);
            $form->text('first_fav_count')->default(0);
            $form->display('created_at');
            $form->display('updated_at');

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();

                // 通过 $result 可以判断数据是否删除成功
                if (!$result) {
                    return $form->response()->error('数据删除失败');
                }

                ArticleComment::where(['article_id' => $data[0]['id']])->delete();

                // 返回删除成功提醒，此处跳转参数无效
                return $form->response()->success('删除成功');
            });
        });
    }
}
